package com.imau.controller;

import com.imau.bean.User;
import com.imau.mapper.UserMapper;
import com.imau.utils.SqlSessionFactoryUtil;

import org.apache.ibatis.session.SqlSession;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setHeader("Content-Type","text/html;charset=UTF-8");
        //1.获取页面传递过来 用户名 和密码
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        int remem=0;
        String remem1 = request.getParameter("remem");
        System.out.println(remem1);
        if(remem1 !=null && !"".equals(remem1) && remem1.length()>0)
        {
             remem    =  Integer.valueOf(remem1 )   ;
        }


        //2.查询数据库
        SqlSession session = SqlSessionFactoryUtil.getInstace().openSession(true);
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.selectByUserNameAndPassword(userName, password);

        session.close();
        if(user == null)//用户名密码错误 跳转到登录页面
        {
//            request.getServletContext().getContextPath()
            response.sendRedirect("/servlet-loginDemo/login.html");

        }else { //跳转到系统


            if(remem==1) {
                Cookie cookie = new Cookie("userName", userName);
                Cookie cookie2 = new Cookie("password", password);
                cookie2.setMaxAge(3600);
                cookie.setMaxAge(3600);
                response.addCookie(cookie);
                response.addCookie(cookie2);
            }else { //删除cookie

                Cookie[] cookies = request.getCookies();


            }
            response.getWriter().write("登录成功!!");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request,response);
    }
}
